/*
* @Author: Administrator
* @Date:   2018-01-08 16:11:08
* @Last Modified by:   Administrator
* @Last Modified time: 2018-01-27 15:39:41
*/
const ejs = require('ejs')
const asyncBootstrap = require('react-async-bootstrapper').default
const serializeJs = require('serialize-javascript')
const ReeactDomServer = require('react-dom/server')

const getStore = (stores) => {
  return Object.keys(stores).reduce((result, storeName) => {
    result[storeName] = stores[storeName].toJson()
    return result
  }, {})
}

const serverRender = (bundleModule, template, req, res) => {
  return new Promise((resolve, reject) => {
    const createApp = bundleModule.default
    const createStore = bundleModule.createStore
    const createUserStore = bundleModule.createUserStore
    const stores = createStore()
    const userStore = createUserStore(req.session.userInfo)
    const context = {}
    const app = createApp(stores, userStore, context, req.url)
    if (context.url) {
      res.status(302).setHeader('Location', routerContext.url)
      res.end()
      return
    }
    asyncBootstrap(app).then(() => {
      const content = ReeactDomServer.renderToString(app)
      const html = ejs.render(template, {
        app: content,
        initialState: serializeJs(getStore(stores)),
        userInfo: serializeJs(req.session.userInfo || {})
      })
      res.send(html)
      resolve()
    }).catch(reject)
  })
}

module.exports = serverRender
